package summary;

import java.util.*;

/**
 * @Author: 海琳琦
 * @Date: 2022/8/28 14:45
 * https://leetcode.cn/problems/minimum-operations-to-make-the-array-alternating/
 */
public class Title2170 {

    public static int minimumOperations(int[] nums) {
        int n = nums.length;
        if (n == 1) {
            return 0;
        }
        //统计出现的次数
        Map<Integer, Integer> evenMap = new HashMap<>();
        Map<Integer, Integer> oddMap = new HashMap<>();
        for (int i = 0; i < n; i++) {
            if (i % 2 != 0) {
                oddMap.put(nums[i], oddMap.getOrDefault(nums[i], 0) + 1);
            }else{
                evenMap.put(nums[i], evenMap.getOrDefault(nums[i], 0) + 1);
            }
        }

        //统计奇偶列的众数
        //<key, 频率>
        List<int[]> evenArr = new ArrayList<>();
        List<int[]> oddArr = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : evenMap.entrySet()) {
            evenArr.add(new int[]{entry.getKey(), entry.getValue()});
        }
        for (Map.Entry<Integer, Integer> entry : oddMap.entrySet()) {
            oddArr.add(new int[]{entry.getKey(), entry.getValue()});
        }
        //排序 按照频率进行排序，频率相等后无所谓
        Collections.sort(evenArr, (a, b) -> Integer.compare(b[1], a[1]));
        Collections.sort(oddArr, (a, b) -> Integer.compare(b[1], a[1]));
        int count;
        if (evenArr.get(0)[0] != oddArr.get(0)[0]) {
            count = n - oddArr.get(0)[1] - evenArr.get(0)[1];
        }else{
            int a1 = evenArr.get(0)[1];
            int a2 = 0;
            if (evenArr.size() != 1) {
                a2 = evenArr.get(1)[1];
            }
            int b1 = oddArr.get(0)[1];
            int b2 = 0;
            if (oddArr.size() != 1) {
                b2 = oddArr.get(1)[1];
            }
            int temp1 = n - a1 - b2;
            int temp2 = n - a2 - b1;
            count = Math.min(temp1, temp2);
            }
        return count;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 2, 2};

        int i = minimumOperations(arr);
        System.out.println(i);
    }
}
